package 个人密码库.util;

import java.util.*;

public class TablePrinter {
    public static void printTable(List<String> headers, List<List<String>> rows) {
        // 计算每一列的最大宽度
        List<Integer> colWidths = new ArrayList<>();
        for (int i = 0; i < headers.size(); i++) {
            int maxWidth = headers.get(i).length();
            for (List<String> row : rows) {
                if (i < row.size()) {
                    maxWidth = Math.max(maxWidth, row.get(i).length());
                }
            }
            colWidths.add(maxWidth);
        }

        // 打印分隔线
        printLine(colWidths);

        // 打印表头
        printRow(headers, colWidths);
        printLine(colWidths);

        // 打印内容
        for (List<String> row : rows) {
            printRow(row, colWidths);
        }
        printLine(colWidths);
    }

    private static void printLine(List<Integer> colWidths) {
        StringBuilder sb = new StringBuilder();
        for (int width : colWidths) {
            sb.append("+").append("-".repeat(width + 2));
        }
        sb.append("+");
        System.out.println(sb);
    }

    private static void printRow(List<String> row, List<Integer> colWidths) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < colWidths.size(); i++) {
            String cell = i < row.size() ? row.get(i) : "";
            sb.append("| ").append(padRight(cell, colWidths.get(i))).append(" ");
        }
        sb.append("|");
        System.out.println(sb);
    }

    private static String padRight(String text, int length) {
        return String.format("%-" + length + "s", text);
    }
}
